<?php
/*! \page license
 *
 * Copyright (c) 2011, Blaise Lengrand
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list
 * of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this
 * list of conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.
 * Neither the name of `snWin' nor the names of its contributors may be used to
 * endorse or promote products derived from this software without specific prior
 * written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
  /*! This file initialize the environement to work with the social module.
   * It also provides a set of helper functions for feed handling.
   */
  // Go to the root directory and initialize the environment
  $prev = "";
  while (!is_dir("system") && getcwd() != $prev)
  {
    $prev = getcwd();
    chdir('..');
  }
  // If the init.php is present (this file host the configuration)
  if (is_file("system/php/init.php"))
  {
    require_once("system/php/init.php");
    init(false);
    // Set page parameters
    global $_PAGE_PARAMS;
    global $_CURRENT;
    $_PAGE_PARAMS = $_CURRENT['pages']['content'];
  }
  else
    die("Missing configuration file");

  /* Automatically strips slashes if magic quotes are enabled */
  if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  {
    global $_POST;
    global $_GET;
    foreach ($_POST as $key => $value)
      $_POST[$key] = stripslashes($_POST[$key]);
    foreach ($_GET as $key => $value)
      $_GET[$key] = stripslashes($_GET[$key]);
  }

  //! Flag to tell if an error is present
  define('FEED_ERROR', -1);
  //! \internal Internal variable to store the last error message
  $feed_error_str = "";
  /*! Read the last error message
   * \return Error message
   */
  function feed_get_error()
  {
    global $feed_error_str;
    return $feed_error_str;
  }
  /*! Set the last error message
   * \param $str The error message
   * \return FEED_ERROR
   */
  function feed_set_error($str)
  {
    global $feed_error_str;
    $feed_error_str = $str;
    return FEED_ERROR;
  }

  /* JSON */

  /*! If the json request result in an error
   */
  function feed_json_error($message)
  {
    header("HTTP/1.0 403 Forbidden");
    echo json_encode(array('Message' => $message));
    die();
  }

  /*! Success on json request
   */
  function feed_json_success($obj)
  {
    header("HTTP/1.0 200 Success");
    echo json_encode($obj);
    die();
  }

  /* Classic */

  /*! Error
   */
  function feed_error($message)
  {
    header("HTTP/1.0 403 Forbidden");
    echo $message;
    die();
  }

  /*! Success
   */
  function feed_success($message)
  {
    header("HTTP/1.0 200 Success");
    echo $message;
    die();
  }

  /*! Send a GET request
   * \param url The URL where to send the request
   * \param data An array containing the data to be sent
   * \param info An array to receive the page info
   */
  function feed_get($url, $data = array(), &$info = -1)
  {
    return feed_request($url, 'GET', $data, $info);
  }

  /*! Send a POST request
   */
  function feed_post($url, $data = array(), &$info = -1)
  {
    return feed_request($url, 'POST', $data, $info);
  }

  /*! \internal
   */
  function feed_request($url, $type = 'GET', $data = array(), &$info = -1)
  {
    // Init the cURL module
    $ch = curl_init();

    // POST or GET request type
    switch ($type)
    {
    case 'POST':
      curl_setopt($ch, CURLOPT_POST, true);
      // Set the data if any
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      break;
    case 'GET':
      // Build the query string
      $query = "";
      $first = 0;
      if ($data)
        foreach ($data as $key => $value)
          $query .= (($first++)?"&":"").$key."=".urlencode($value);
      if ($query)
        $url .= "?".$query;
      break;
    }

    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

    // Send the request and grab the result
    $result = curl_exec($ch);
    if (!$result)
      return feed_set_error("Couldn't send the request: ".curl_error());

    // If info is set, fill the array
    if ($info != -1)
      $info['content_type'] = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

    // Close cURL resource, and free up system resources
    curl_close($ch);
    // Check for error in the result
    if (preg_match("/error/i", $result))
      return feed_set_error($result);

    // Returns the result
    return $result;
  }
?>
